/**
 * 
 */
package com.et114.modules.org.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.et114.components.acegi.Constants;
import com.et114.components.acegi.cache.AcegiCacheManager;
import com.et114.components.ectable.EXTableUtils;
import com.et114.components.ectable.EctableConverts;
import com.et114.components.ectable.MultipleSelectedCell;
import com.et114.components.tree.tree51.BaseTree51Model;
import com.et114.core.action.BaseDispatchAction;
import com.et114.core.common.CONST;
import com.et114.core.common.Error;
import com.et114.core.utility.ArgumentTokenizer;
import com.et114.core.utility.StringPool;
import com.et114.modules.org.form.FuncCompForm;
import com.et114.modules.org.message.FuncMessageManager;
import com.et114.modules.org.message.OrgMessageManager;
import com.et114.modules.org.services.FunctionManager;
import com.et114.modules.org.services.GroupManager;
import com.et114.modules.org.services.OrgFactory;
import com.et114.modules.org.utility.SessionUserInfo;
import com.et114.modules.org.vo.AclVo;
import com.et114.modules.org.vo.FuncComponentVo;
import com.et114.modules.org.vo.FunctionVo;
import com.et114.modules.org.vo.GroupVo;
import com.et114.modules.org.vo.RoleVo;
import com.et114.modules.org.vo.TitleMsgVo;
import com.et114.modules.system.dictionary.DictionaryCache;
import com.et114.modules.system.dictionary.vo.BizOption;

import org.apache.commons.beanutils.PropertyUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
 
/*
 * @author guanhw
 */
public class FuncCompAction extends BaseDispatchAction {
	private static String _LU = Constants.RESOURCE_DO_AUTH_USER ; 
	private static String _LR = Constants.RESOURCE_DO_AUTH_ROLE ;
	private static String _LT = Constants.RESOURCE_DO_AUTH_TITLE ;
	private final String VALID_C_GROUPS_KEY = "__fw_cgroupMap"  ;
	private final String GROUPS_C_KEY = "__fw_cgroups"  ;
	
	
	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward loadFuncComps ( ActionMapping mapping ,
			ActionForm form , HttpServletRequest request ,
			HttpServletResponse response ) throws Exception {
		FuncCompForm fcf = ( FuncCompForm ) form ;
		FunctionManager fm = OrgFactory.getFunctionManager ( ) ;
		Long funcId = fcf.getFuncId ( ) ; 
		if ( funcId != null && funcId.longValue ( ) != 0 ) {
			List fcs = fm.getFunctionCompsWithCountRel ( funcId ) ;
			FunctionVo fVo = fm.getFunc ( funcId ) ;
			// vaild 检查菜单是否为空
			if ( fVo == null  ) {
				error.setErrorTitle ( FuncMessageManager.get ( ).getMessage ( "org.func.isnull" , request.getLocale ( ) ) );
				request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
				return mapping.findForward( "glerror" ) ;								
			}						
			request.setAttribute ( "pfc" , fVo ) ;
			request.setAttribute ( "fcs" , fcs ) ; 
		}
		return mapping.findForward ( "toFuncComps" ) ;
	}
	
	/***
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward loadFuncComp ( ActionMapping mapping ,
			ActionForm form , HttpServletRequest request ,
			HttpServletResponse response ) throws Exception {
		FuncCompForm fcf = ( FuncCompForm ) form ;
		FunctionManager fm = OrgFactory.getFunctionManager ( ) ;
		
		Long ffId = fcf.getFuncElementId ( );
		if ( ffId != null && ffId .longValue ( ) != 0 ) {
			FuncComponentVo fcv = fm.getFuncComp ( ffId ) ;
			// vaild 检查菜单是否为空
			if ( fcv == null  ) {
				error.setErrorTitle ( FuncMessageManager.get ( ).getMessage ( "org.func.isnull" , request.getLocale ( ) ) );
				request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
				return mapping.findForward( "glerror" ) ;								
			}						
			request.setAttribute ( "vo" , fcv ) ;
		}
		
		return mapping.findForward ( "loadFuncComp" ) ;
	}
	

	
	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward loadFuncCompsr ( ActionMapping mapping ,
			ActionForm form , HttpServletRequest request ,
			HttpServletResponse response ) throws Exception {
		loadFuncComps( mapping , form , request , response ) ;
		return mapping.findForward ( "toFuncCompsLeft" ) ;
	}
	
	public ActionForward toFuncCompAuthIndex ( ActionMapping mapping ,
			ActionForm form , HttpServletRequest request ,
			HttpServletResponse response ) throws Exception {
		loadFuncComps( mapping , form , request , response ) ;
		return mapping.findForward ( "indexAuths" ) ;
	}	
	
	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws NoSuchMethodException 
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * @throws Exception 
	 * @throws Exception
	 */
	public ActionForward addFuncComps ( ActionMapping mapping ,
			ActionForm form , HttpServletRequest request ,
			HttpServletResponse response ) throws Exception { 
		SessionUserInfo currentUser = getCurrentUser ( request ) ; 
		FuncCompForm fcf = ( FuncCompForm ) form ;
		//vaild
		String url = fcf.getTargetUrl ( );
		StringTokenizer sts = new StringTokenizer( url , Constants.URL_RESOURCES_SPLIT ) ;
		String res = null ; 
		while( sts.hasMoreElements ( ) ) {
			String st = sts.nextElement ( ).toString ( ) ;  
			if ( st != null && !Constants.NULL_URL .equals ( st.trim ( ) ) && !"".equals ( st.trim ( ) )   ){
				res = AcegiCacheManager.getInstansce ( ).cacheAntContains ( st ) ; 
				if ( res != null ) {
					Error error = new Error ( );
					error.setErrorTitle ( OrgMessageManager.get ( ).getMessage ( "org.funcurl.exist" ,request.getLocale ( )   ) ); 
					request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY ,	error );
					break ;		
				}							
			}
		}
		//
	
		FunctionManager fm = OrgFactory.getFunctionManager ( ) ;
		
		Long  funcElementId  = fcf.getFuncElementId ( ) ; 
		FuncComponentVo fcv = new FuncComponentVo();
		PropertyUtils.copyProperties ( fcv , fcf ) ;
		if ( funcElementId != null && funcElementId .longValue ( ) != 0   ) { // update
			FuncComponentVo vo = fm.getFuncComp ( fcv.getFuncElementId ( ) );
			if ( vo == null  ) {
				error.setErrorTitle ( FuncMessageManager.get ( ).getMessage ( "org.func.isnull" , request.getLocale ( ) ) );
				request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
				return mapping.findForward( "glerror" ) ;								
			}						
			//TODO:if ( !vo.getTargetUrl ( ).equals ( url ) && res != null ) return mapping.findForward( "glerror" ) ;
			if (  !vo.getCode ( ).equals ( fcv.getCode ( ) ) ) {
				if ( fm.countFuncComps( fcv ) > 0 ) {
					error.setErrorTitle ( OrgMessageManager.get ( ).getMessage ( "org.functionComp.already.exist" ) );
					request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
					return mapping.findForward( "glerror" ) ;
				}
			}
			fcv.setUpdtUser ( currentUser.getUserId ( ) ) ; 
			fm.updateFuncComp ( fcv ) ;
		}
		else { //new
			// vaild 检查菜单是否为空
			if ( res != null )  return mapping.findForward( "glerror" ) ;
			Long funcId = fcf.getFuncId ( ) ; 
			if ( funcId == null || funcId.longValue ( ) == 0L || fm.getFunc ( funcId ) == null ) {
				error.setErrorTitle ( FuncMessageManager.get ( ).getMessage ( "org.func.isnull" , request.getLocale ( ) ) );
				request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
				return mapping.findForward( "glerror" ) ;												
			}
			
			fcv.setCrtUser (  currentUser.getUserId ( ) ) ;
			if ( fm.countFuncComps ( fcv ) > 0  ) {
				error.setErrorTitle ( OrgMessageManager.get ( ).getMessage ( "org.functionComp.already.exist" ) );
				request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
				return mapping.findForward( "glerror" ) ;
			}
			fm.addFuncComp ( fcv ) ;	
			StringBuffer to  = new StringBuffer( "funcSuccess.go?type=funcComp" ) ; 
			if ( fcf.getFuncId ( ) != null && fcf.getFuncId ( ).longValue ( ) != 0 ) {
				to.append ( "&funcId=" ) .append ( fcf.getFuncId ( ) ) ;
			}
			return new ActionForward( to.toString ( ) , true ) ;
		}
		return mapping.findForward ( "glsuccess" ) ;
	}
	
	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws UnsupportedEncodingException 
	 * @throws Exception
	 */
	public ActionForward deleteFuncComps ( ActionMapping mapping ,
			ActionForm form , HttpServletRequest request ,
			HttpServletResponse response ) throws Exception {
		StringBuffer  to = new StringBuffer( "funcComp.go?method=loadFuncComps&funcId=" )  ;
		
		FuncCompForm fcf = ( FuncCompForm ) form ;
		FunctionManager fm = OrgFactory.getFunctionManager ( ) ;

		to = to.append ( fcf.getFuncId ( ) ) ; 
		String params = EXTableUtils.getLimitParams ( request ) ;
		to.append ( params ) ;
		
		
		Long[] ids = fcf.getDeleteId ( );
		if ( ids != null ) {
			for ( int i = 0 ; i < ids .length ; i ++ ) {
				fm.deleteFuncComp ( ids[ i ] , getCurrentUser ( request ).getUserId ( ) ) ;
			}
		}
		
		return new ActionForward( to.toString ( ) , true  ) ;
	}
	
	
	/**
	 * 生成授权首页 
	 */
	public  ActionForward indexRoleAuths ( ActionMapping mapping, ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
			List soptions = OrgFactory.getRoleManager ( ).getRoleTypes (  )  ;
			request.setAttribute ( "options" , soptions ) ;	
			return mapping.findForward (  "indexRolesAuths"  ) ;
	}		
	  
	public  ActionForward loadAuths( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		SessionUserInfo currentUser = getCurrentUser ( request ) ; 
		byte currentUserMaxRoleType =  currentUser.getUserRoleType ( ) ; 
		FuncCompForm fcf = ( FuncCompForm ) form ;
		FunctionManager fm = OrgFactory.getFunctionManager ( ) ;
		
		FuncComponentVo vo = new FuncComponentVo( ) ; 
		PropertyUtils.copyProperties ( vo , fcf ) ; 
		
		List ls = new ArrayList();
		String _m = request.getParameter ( "_m" ) ; 
		List authTypes = DictionaryCache.getInstance ( ).listBizOptions ( Constants.RESOURCE_DO_AUTH_KEY , false )   ;
		
		if ( _m == null || "".equals ( _m.trim ( ) ) ) {
			if ( authTypes.size ( ) > 0 ) _m = ( ( BizOption ) authTypes.get ( 0 ) ).getOptionValue ( ) ;
		}
		if ( authTypes.size ( ) == 2 && currentUserMaxRoleType == Constants.ROLE_TYPE_ORG_MANAGER ) {
			_m = Constants.RESOURCE_DO_AUTH_TITLE ; 
			List tmpAt = new ArrayList( 0 ) ; 
			tmpAt.addAll ( authTypes ) ; 
			for ( java.util.Iterator iter = tmpAt.iterator ( ) ; iter.hasNext ( ) ;  ) {
				String v = ( ( BizOption ) iter.next ( ) ).getOptionValue ( );
				if ( v .equals ( Constants.RESOURCE_DO_AUTH_ROLE ) ) 
					iter.remove ( ) ; 
			}		
			request.setAttribute ( "authTypes" , tmpAt ) ;
		}			

		Long fId = fcf.getFuncElementId ( ) ; 
		if ( fId != null && fId .longValue ( ) != 0  ) {
			//do delete
			if ( _LU.equals ( _m ) ) { //user
				ls = fm.getUsersByFuncCompId ( fId ) ;
			}
			else if ( _LR.equals ( _m ) ) { //role
				vo.setRoleType ( currentUserMaxRoleType ) ;

		        EctableConverts  ec = vo.getEconverts ( ) ; 
		        ec.setProConvert ( "authDate" , "a.crtTime" ) ;
		        ec.setProConvert ( "roleName" , "b.roleName" ) ;
		        
				EXTableUtils.initLimitPage(  vo , request ) ;
				Long rl = fm.countgetRolesByFunctionComp ( vo ) ;
				vo.setTotalRows ( rl.intValue ( ) ) ;
				EXTableUtils.setLimitRowAttributes(  vo , request ) ;
				ls = fm.getRolesByFuncComp ( vo , CONST.PAGE ); // 大于roleType
				
				if ( vo.getRoleName ( ) != null ) request.setAttribute ( "roleName" , vo.getRoleName ( ) ) ;
				if ( vo.getStartTime ( ) != null ) request.setAttribute ( "startTime" , vo.getStartTime ( ) ) ;
				if ( vo.getEndTime ( ) != null ) request.setAttribute ( "endTime" , vo.getEndTime ( ) ) ;	
			}
			else if ( _LT.equals ( _m ) ) { //title
				Long grpId = fcf.getGrpId ( ) ; 
				Map groupMap = new HashMap( ) ; 
				Map roots = new HashMap( ) ; 
				GroupManager groupManager = OrgFactory.getGroupManager ( );
				List groups = new ArrayList( 1  )  ;
				
				groups.addAll ( (  request.getSession ( ).getAttribute (  GROUPS_C_KEY  ) != null  ? ( List ) request.getSession ( ).getAttribute (  GROUPS_C_KEY  ) : new ArrayList( ) ) ) ;
				groupMap.putAll ( (  request.getSession ( ).getAttribute (  VALID_C_GROUPS_KEY  ) != null  ? ( Map ) request.getSession ( ).getAttribute (  VALID_C_GROUPS_KEY  ) : new HashMap() )  ) ;
				
				
				if ( authTypes.size ( ) == 2 ) { // role title
					if ( currentUserMaxRoleType == Constants.ROLE_TYPE_ORG_MANAGER
							&& ( groups.size ( ) == 0 || groupMap.size ( ) == 0 ) ) {
						List roles = OrgFactory.getUserManager ( ).getAllRolesByUserParams  (
								Constants.ROLE_TYPE_ORG_MANAGER ,
								currentUser.getUserId ( ) );
						if ( roles.size ( ) > 0 ) {
							StringBuffer roleIds = new StringBuffer() ;
							for ( int i = 0 ; i < roles.size ( ) ; i ++ ) {
								RoleVo role = ( RoleVo ) roles.get ( i ) ;
								roleIds.append ( role.getRoleId ( ).toString ( ) )  ;
								if ( ( i + 1 ) != roles.size ( ) ) roleIds.append ( StringPool.COMMA )  ;
							}
							if ( roleIds.length ( ) > 0 ) {
								roots = OrgFactory.getRoleManager ( ).getGroupsAnByRoles ( roleIds.toString ( ) ) ;
								groupMap.putAll ( roots ) ; 
								groups.addAll ( OrgFactory.getRoleManager ( ).getRootsGroupsByRolesSorts( roots ) ) ; 
							}
						} 			
					}
					else if ( currentUserMaxRoleType < Constants.ROLE_TYPE_ORG_MANAGER ) 
						groups.add ( groupManager.loadGroup4SelectOption ( grpId )  ) ;
				}
				else  throw new Exception( Constants.AUTH_ACCESSDENIED ) ;  
					
				GroupVo groupVo = null ; 
				if (  ( authTypes.size ( ) == 2 && ( grpId == null || grpId.longValue ( ) == 0L ) ) ) {
					groupVo = ( GroupVo )groups.get ( 0 ) ; 
					groupVo.setParentGroupVo ( null ) ; 
					groupVo.setFgrpId ( null ) ;
				}
				else{
					//check
					groupVo = groupManager.loadGroup4SelectOption ( grpId ) ;
					if (  authTypes.size ( ) == 2 && currentUserMaxRoleType == Constants.ROLE_TYPE_ORG_MANAGER ) {
						if ( groupMap != null && !groupMap.containsKey ( groupVo.getGrpId ( ) ) ) throw new Exception( Constants.AUTH_ACCESSDENIED ) ;
						if ( roots.containsKey ( groupVo.getGrpId ( ) ) ) groupVo.setFgrpId ( null ) ;
						request.setAttribute ( "noRole" , "noRole" ) ; 
					}						
					
				} 
				

				ls = groupVo.getTitleList ( );				
	
				List l = fm.getTitlesByFunc ( fm.getFunc ( vo.getFuncId ( ) )  ) ;
				ls.retainAll ( l ) ;
				List selectedTitleList = fm.getTitlesByFuncCompId ( fId ); // TODO
				StringBuffer sb = new StringBuffer( StringPool.SEMICOLON ) ; 
				for ( java.util.Iterator iter = selectedTitleList.iterator ( ) ; iter.hasNext ( ) ;  ) {
					TitleMsgVo title = ( TitleMsgVo ) iter.next ( ) ;
					Long id = title.getTitleId ( ) ;
					java.util.Date authDate = title.getAuthDate ( ) ; 
					for ( java.util.Iterator _iter = ls.iterator ( ) ; _iter.hasNext ( ) ;  )   {
						title = ( TitleMsgVo ) _iter.next ( ) ;
						if ( title.getTitleId ( ).equals ( id ) ) {
							title.setAuthDate ( authDate ) ;
							sb.append ( title.getTitleId ( ) ).append ( StringPool.SEMICOLON )  ;
							break ;
						}
					}
				}
				//
				boolean mark = false ; 
				for ( java.util.Iterator iter = groups.iterator ( ) ; iter.hasNext ( ) ;  ) {
					GroupVo group__ = ( GroupVo ) iter.next ( ) ;
					if ( group__.getGrpId ( ).equals (  groupVo.getGrpId ( ) ) ) {
						iter.remove ( ) ;
						mark = true ; 
						break ; 
					}
					else mark = false ; 
				}
				if ( mark == false  ) groups.clear ( ) ;  
				
				
				request.setAttribute ( "groups" , groups ) ; 				
				request.setAttribute ( "_m" , "title" );
				request.setAttribute ( "groupVo" , groupVo );
				request.setAttribute (	MultipleSelectedCell.SELECTED_PRESIDENTS ,	sb.toString ( ) );				
			}
			request.setAttribute ( Constants.CURRENT_URSER_MAX_ROLETYPE , new Integer( currentUserMaxRoleType ) ) ;
			request.setAttribute ( "ls" , ls ) ;
			request.setAttribute ( "_m" , _m ) ;
			
			
			//TODO //TODO second判断分散岗位授权
			String titleForward = "/modules/system/funcCompAuthsTitles.jsp";
			if ( request.getAttribute ( "authTypes" ) == null )
				request.setAttribute ( "authTypes" , authTypes );
			else if ( request.getParameter ( "second" ) == null )
				titleForward = "/funcComp.go?method=loadTitleAuthsIndex&_m=title&funcId="
						+ fcf.getFuncId ( )
						+ "&funcElementId"
						+ fcf.getFuncElementId ( );

			if ( Constants.RESOURCE_DO_AUTH_TITLE.equals ( _m ) ) return new ActionForward( titleForward ) ; 
			
		}
		return mapping.findForward ( "loadAuthsRight" ) ;
	}
	
	
	public  ActionForward loadTitleAuthsIndex( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {

		SessionUserInfo currentUser = getCurrentUser ( request ) ;
		byte currentUserMaxRoleType =  currentUser.getUserRoleType ( ) ; 
		String _m = request.getParameter ( "_m" ) ; 
		List authTypes = DictionaryCache.getInstance ( ).listBizOptions ( Constants.RESOURCE_DO_AUTH_KEY , false )   ;
		
		if ( _m == null || "".equals ( _m.trim ( ) ) ) {
			if ( authTypes.size ( ) > 0 ) _m = ( ( BizOption ) authTypes.get ( 0 ) ).getOptionValue ( ) ;
		}
		if ( authTypes.size ( ) == 2 && currentUserMaxRoleType == Constants.ROLE_TYPE_ORG_MANAGER ) {
			_m = Constants.RESOURCE_DO_AUTH_TITLE ; 
			List tmpAt = new ArrayList( 0 ) ; 
			tmpAt.addAll ( authTypes ) ; 
			for ( java.util.Iterator iter = tmpAt.iterator ( ) ; iter.hasNext ( ) ;  ) {
				String v = ( ( BizOption ) iter.next ( ) ).getOptionValue ( );
				if ( v .equals ( Constants.RESOURCE_DO_AUTH_ROLE ) ) 
					iter.remove ( ) ; 
			}		
			request.setAttribute ( "authTypes" , tmpAt ) ;
		}	
		request.setAttribute ( Constants.CURRENT_URSER_MAX_ROLETYPE , new Integer( currentUserMaxRoleType ) ) ;		
		if ( request.getAttribute ( "authTypes" ) == null ) request.setAttribute ( "authTypes" , authTypes ) ;

		return new ActionForward( "/modules/system/funcCompAuthsTitleIndex.jsp" ) ; 
	}
		
	
	public ActionForward loadChildGroups( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
			FuncCompForm ff = ( FuncCompForm ) form ;
			Long grpId = ff.getGrpId ( ) ; 
			GroupManager groupManager = OrgFactory.getGroupManager ( );
			List groups = groupManager.getChildGroup ( grpId ) ; 
			String tree = OrgFactory.getFunctionManager ( ).generateGroupTreeStr (  true , groups ,
					String.valueOf ( grpId ) , BaseTree51Model.IS_TARGET_Y , request.getLocale ( ) ,
					ff.getFuncId ( ) , ff.getFuncElementId ( ) );
			request.setAttribute ( "partyTree" , tree ) ; 
			
			return new ActionForward( "/modules/org/partyTree.jsp" ) ;
	}	
	
	public ActionForward loadTitleAuthsGroups( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
	    request.getSession ( ).removeAttribute (  VALID_C_GROUPS_KEY  ) ;
	    request.getSession ( ).removeAttribute (  GROUPS_C_KEY  ) ;

		
		FuncCompForm fcf = ( FuncCompForm ) form ;
		SessionUserInfo currentUser = getCurrentUser ( request ) ;
		byte currentUserMaxRoleType =  currentUser.getUserRoleType ( ) ; 
		Map groupMap = new HashMap( ) ; 
		Map roots = new HashMap( ) ; 

		GroupManager groupManager = OrgFactory.getGroupManager ( );
		List groups = new ArrayList( 0  )  ;


		if ( currentUserMaxRoleType == Constants.ROLE_TYPE_ORG_MANAGER  ) {
			List roles = OrgFactory.getUserManager ( ).getAllRolesByUserParams  (
					Constants.ROLE_TYPE_ORG_MANAGER ,
					currentUser.getUserId ( ) );
			if ( roles.size ( ) > 0 ) {
				StringBuffer roleIds = new StringBuffer() ;
				for ( int i = 0 ; i < roles.size ( ) ; i ++ ) {
					RoleVo role = ( RoleVo ) roles.get ( i ) ;
					roleIds.append ( role.getRoleId ( ).toString ( ) )  ;
					if ( ( i + 1 ) != roles.size ( ) ) roleIds.append ( StringPool.COMMA )  ;
				}
				
				if ( roleIds.length ( ) > 0 ) {
					roots = OrgFactory.getRoleManager ( ).getGroupsAnByRoles ( roleIds.toString ( ) ) ;
					groupMap.putAll ( roots ) ; 
					request.getSession ( ).setAttribute ( VALID_C_GROUPS_KEY , groupMap ) ; 
					groups.addAll ( OrgFactory.getRoleManager ( ).getRootsGroupsByRolesSorts( roots ) ) ; 
				}							
			} 		
		}
		else if ( currentUserMaxRoleType < Constants.ROLE_TYPE_ORG_MANAGER ) 
			groups.add ( groupManager.loadGroup4SelectOption ( new Long  ( Constants.ORG_GROUP_BASE_VALUE ) )  ) ;
		
		request.getSession ( ).setAttribute ( GROUPS_C_KEY , groups ) ; 
		
		String cugid = ( ( GroupVo ) groups.get ( 0 ) ).getGrpId ( ).toString ( ) ;
		String tree = OrgFactory.getFunctionManager ( ).generateGroupTreeStr(  false , groups , cugid , BaseTree51Model.IS_TARGET_Y , request.getLocale ( ) , fcf.getFuncId ( ) , fcf.getFuncElementId ( ) ) ; 
		request.setAttribute ( "partyTree" , tree ) ; 
		
	

		return new ActionForward( "/modules/org/partyTree.jsp" ) ;		
	}
	
	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public  ActionForward loadRoleAuths( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		FuncCompForm fcf = ( FuncCompForm ) form ;
		FunctionManager fm = OrgFactory.getFunctionManager ( ) ;

		Long funcId = fcf.getFuncId ( );
		if ( funcId != null && funcId.longValue ( ) != 0  ) {
			List ls = new ArrayList();
			FunctionVo vo = fm.getFunc ( funcId ) ;
			vo.setRoleType ( fcf.getRoleType ( ) ) ; 
			ls = fm.getRolesByFunc ( vo ) ;
			request.setAttribute ( "roles" , ls ) ; 
		}
		FuncComponentVo vo = new FuncComponentVo( ) ; 
		PropertyUtils.copyProperties ( vo , fcf ) ; 
		List ls = fm.getRolesByFuncCompo ( vo ); //等于
		request.setAttribute ( "ls" , ls ) ;
		return mapping.findForward ( "toRolesAuths" ) ;
	}
	

	
	/**
	 * TODO 移到buz层
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public  ActionForward doRoleAuths( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		SessionUserInfo currentUser = getCurrentUser ( request ) ; 
		
		FuncCompForm fcf = ( FuncCompForm ) form ;
		if ( fcf.getRoleType ( ) == 0  ) return mapping.findForward ( "glerror" ) ; 
		
		FunctionManager fm = OrgFactory.getFunctionManager ( ) ;
		
		Long funcId = fcf.getFuncId ( ); 
		Long funcCompId = fcf.getFuncElementId ( ) ;
		String principalIds = fcf.getPrincipalIds ( );
		String principalType = fcf.getPrincipalType ( ) ; 
		
		long currentTime = System.currentTimeMillis ( ) ; 
		FuncComponentVo func = fm.getFuncComp ( funcCompId ) ;
		// vaild 检查菜单是否为空
		if ( func == null  ) {
			error.setErrorTitle ( FuncMessageManager.get ( ).getMessage ( "org.func.isnull" , request.getLocale ( ) ) );
			request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
			return mapping.findForward( "glerror" ) ;												
		}

		func.setRoleType ( fcf.getRoleType ( ) ) ;  
		//SINCE 1.36
		fm.saveRoleAuthorize( func , principalIds , currentUser.getUserId ( )  ) ;
		logger.debug ( "FuncComp Auth ..." + ( System.currentTimeMillis ( ) - currentTime ) ) ;
		
		StringBuffer to = new StringBuffer() ; 
		to.append ( "funcComp.go?method=loadRoleAuths" ) ;
		to.append ( "&_m=" ).append ( principalType ) ;
		to.append ( "&funcId=" ).append ( funcId ) ;
		to.append ( "&funcElementId=" ).append ( funcCompId ) ;
		to.append ( "&roleType=" ).append ( fcf.getRoleType ( ) ) ;
		return new ActionForward( to.toString ( ) , true ) ;
	}
	
	//TODO
	public ActionForward saveTitleAuths ( ActionMapping mapping ,
			ActionForm form , HttpServletRequest request ,
			HttpServletResponse response ) throws Exception {
		SessionUserInfo currentUser = getCurrentUser ( request );
		FunctionManager functionManager = OrgFactory.getFunctionManager ( ) ;
		GroupManager groupManager = OrgFactory.getGroupManager ( );

		FuncCompForm fcf = ( FuncCompForm ) form ;
		Long funcId = fcf.getFuncId ( ) ;
		Long funcElId = fcf.getFuncElementId ( ) ; 
		if ( funcId == null || funcId.longValue ( ) == 0 ) 
			throw new Exception( "funcId is null !" ) ;
		if ( fcf.getGrpId ( ) == null || fcf.getGrpId ( ).longValue ( ) == 0  ) 
			throw new Exception( "grpId is null !" ) ;
		
		FuncComponentVo funcComp = functionManager.getFuncComp ( funcElId ) ;
		FunctionVo functionVo = functionManager.getFunc ( funcId ) ; 
		// vaild 检查菜单是否为空
		if ( funcComp == null || functionVo == null ) {
			error.setErrorTitle ( FuncMessageManager.get ( ).getMessage ( "org.func.isnull" , request.getLocale ( ) ) );
			request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
			return mapping.findForward( "glerror" ) ;											
		}
		funcComp.setCrtUser ( currentUser.getUserId ( ) );
		funcComp.setParent ( functionVo ) ;
		String selecttitleIds = request.getParameter ( MultipleSelectedCell.SELECTED_PRESIDENTS ) ;
		List chkdTitleList = new ArrayList ( );
		if ( selecttitleIds != null && !selecttitleIds.trim ( ).equals ( StringPool.SEMICOLON ) ) {
			selecttitleIds = selecttitleIds.substring ( 1  , selecttitleIds.length ( ) - 1  ) ;
			ArgumentTokenizer at = new ArgumentTokenizer( selecttitleIds ,  StringPool.CHAR_SEMICOLON ) ;
			int i = 0 ; 
			Long[] titleIds = new Long[ at.countTokens ( ) ] ; 
			while( at.hasNext ( ) ) {
				//chkdTitleList.add ( groupManager.loadTitle ( Long.valueOf ( at.next ( ) ) ) );
				titleIds[ i ] = Long.valueOf ( at.next ( ) ) ; 
				i ++ ;
			}
			if ( titleIds .length > 0 )
				chkdTitleList.addAll ( groupManager.queryTitlesByIds( titleIds ) ) ;
		}
		funcComp.setTitles ( chkdTitleList );
		
		functionManager.saveTitleAuths ( fcf.getGrpId ( ) , funcComp ) ;
		StringBuffer to = new StringBuffer() ; 
		//TODO
		to.append ( "funcComp.go?method=loadAuths&second=y&_m=title" ).append ( "&funcId=" )
				.append ( funcId ).append ( "&grpId=" ).append ( fcf.getGrpId ( ) )
				.append ( "&funcElementId=" ).append ( funcElId ) ;
		
		return new ActionForward( to.toString ( ) , true ) ;
	}	
	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws UnsupportedEncodingException 
	 * @throws Exception
	 */
	public  ActionForward deleteAuths( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws  Exception {
		StringBuffer to = new StringBuffer( "funcComp.go?method=loadAuths&funcElementId=" ) ; 
		FuncCompForm fcf = ( FuncCompForm ) form ;
		FunctionManager fm = OrgFactory.getFunctionManager ( ) ;
		
		String _m = request.getParameter ( "_m" ) ; 
		Long funcElementId = fcf.getFuncElementId ( );
		Long funcId = fcf.getFuncId ( );
		Long [] ds = fcf.getDeleteId ( ) ; 
		
		AclVo acl = new AclVo () ;
		acl.setResourceType ( Constants.RESOURCE_COMPONENT ) ;
		acl.setResourceId (  funcElementId ) ;		
		if ( funcElementId != null && funcElementId.longValue ( ) != 0 &&  ds != null ) {
			for ( int i = 0 ; i < ds.length ; i ++  ) {
				if ( _LU.equals ( _m ) ) { //user
					acl.setPrincipalId ( ds[ i ] ) ; 
					acl.setPrincipalType ( Constants.PRINCIPALID_USER ) ;
				}
				else if ( _LR.equals ( _m ) ) { //role
					acl.setPrincipalId ( ds[ i ] ) ; 
					acl.setPrincipalType ( Constants.PRINCIPALID_ROLE ) ;
				}
				else if ( _LT.equals ( _m ) ) { //title
					acl.setPrincipalId ( ds[ i ] ) ;
					acl.setPrincipalType ( Constants.PRINCIPALID_TITLE ) ;
				}			
				//since 1.36
				fm.deleteFuncCompAuthorize ( acl ) ;
			}
		}
		to.append ( funcElementId ).append ( "&_m="  ).append ( _m ) ; 
		to.append ( "&funcId=" ).append ( funcId ) ;
		
		String params = EXTableUtils.getLimitParams ( request ) ;
		to.append ( params ) ;
		String ecp = request.getParameter ( "ec_p_" ) ;
		if ( ecp != null && !"".equals ( ecp ) ) to.append ( "&ec_p_=" ).append ( ecp ) ;						
		return new ActionForward( to.toString ( ) , true ) ;
	}	
}